<template>
  <div class="bar">
    <div class="bar-header">
      <div>
        <span>时间范围: </span>
        <a-month-picker
          placeholder="选择年月"
          @change="onChange"
          v-model="timeModel"
        />
      </div>
      <div class="bar-header-btnClass">
        <a-button type="primary" @click="statisticClick" class="btn"
          >统计</a-button
        >
        <a-button @click="resetClick" class="btn">重置</a-button>
        <a-button @click="exportData" class="btn">导出</a-button>
      </div>
    </div>
    <div class="chart-main mt20 mb20" ref="chartInstance"></div>
  </div>
</template>

<script>
import { exportOprationStatistics } from '@/api/oprationStatistics'
import mixinsBackStack from '@/views/backstageSupport/mixins'
import { getMonthOprationStatistics } from '@/api/oprationStatistics'
var date = new Date();
const nowTime = date.getFullYear() + '-' + Number(date.getMonth() + 1)

export default {
  mixins: [mixinsBackStack],

  data() {
    return {
      time: '',
      chartInstance: null,
      xData: [],
      yData: [],
      timeModel: ''
    }
  },
  components: {
  },
  mounted() {
    // window.addEventListener('resize', () => this.resizeChart())
    this.getCounts()
  },
  methods: {
    async exportData() {
      const createTime = this.time || nowTime
      const { msg } = await exportOprationStatistics({ createTime: createTime + '-1 00:00:00' })
      const a = document.createElement('a')
      a.href = msg
      a.download = '在线业务办理情况统计'
      a.click()
    },
    async getCounts(beginTime) {
      //默认使用当前时间
      const createTime = beginTime || nowTime
      const data = await getMonthOprationStatistics({ createTime: createTime + '-1 00:00:00' })
      this.xData = []
      Object.values(data).forEach(item => {  //获取所有有数据的天数
        item.data.forEach(ele => {
          if (this.xData.indexOf(ele.remark) === -1) this.xData.push(ele.remark)
        })
      })
      this.xData.sort()
      const ydata = {}
      Object.values(data).forEach((item, num) => {  //将数据对应的天数放在数据上，没有的补0
        const tem = new Array(this.xData.length).fill(0);
        ydata[num] = item.data.reduce((pre, cur) => {
          this.xData.forEach(() => {
            let have = this.xData.indexOf(cur.remark)
            tem[have] = Number(cur.count)
          })
          pre = tem
          return pre
        }, [])
      })
      this.yData = ydata
      this.getChart()
    },
    getChart() {
      if (this.chartInstance) {
        this.chartInstance.dispose()
      }
      this.chartInstance = this.$echarts.init(this.$refs.chartInstance)
      let option = {
        color: ['#EF4864', '#F4A419', '#3CBE89', '#557cff', '#1890ff'],
        tooltip: {
          confine: true,
          trigger: 'axis',
          axisPointer: { // 坐标轴指示器，坐标轴触发有效
            type: 'shadow', // 默认为直线，可选为：'line' | 'shadow'
          },
        },
        grid: {
          left: '5%',
          right: '4%',
          bottom: '10%',
          top: '10%',
        },
        legend: {
          icon: 'rect',
          orient: 'horizontal',
          left: 'right',
          itemWidth: 12,
          itemHeight: 12,
          formatter: ['{a|{name}}'].join('\n'),
          textStyle: {
            fontSize: 12,
            color: '#6A93B9',
            height: 8,
            rich: {
              a: {
                verticalAlign: 'bottom',
              },
            },
          },
          data: ['知识产权人民调解', '维权援助', '海外知识产权纠纷指导', '商标监测预警服务', '专利导航预警服务'],
        },
        xAxis: {
          type: 'category',
          // name: '日期',
          axisLine: {
            lineStyle: {
              color: '3333',
            },
          },
          axisLabel: {
            fontSize: 12,
            color: '#6A93B9',
          },
          data: this.xData,
        },
        yAxis: {
          name: '单位:人次',
          type: 'value',
          nameTextStyle: {
            fontSize: 12,
            color: '#33333',
            align: 'center',
          },
          axisLine: { show: true },
          axisTick: { show: false },
          splitArea: { show: false },
          splitLine: {
            lineStyle: {
              color: '#3333',
            },
          },
          axisLabel: {
            fontSize: 12,
            color: '#6A93B9',
            fontFamily: 'Bebas',
          },
        },
        series: [
          { name: '知识产权人民调解', type: 'bar', barWidth: 25, stack: 'total', data: this.yData['0'], },
          { name: '维权援助', type: 'bar', barWidth: 25, stack: 'total', data: this.yData['1'], },
          { name: '海外知识产权纠纷指导', type: 'bar', barWidth: 25, stack: 'total', data: this.yData['2'], },
          { name: '商标监测预警服务', type: 'bar', barWidth: 25, stack: 'total', data: this.yData['3'] },
          { name: '专利导航预警服务', type: 'bar', barWidth: 25, stack: 'total', data: this.yData['4'] },
        ],
      };
      this.chartInstance.setOption(option)
      // 下面的是自适应屏幕大小去缩放
      this.$nextTick(() => {
        setTimeout(() => this.resizeChart(), 500)
      })

    },
    onChange(date, dateString) {
      this.time = dateString
    },
    statisticClick() {
      this.getCounts(this.time)
    },
    resetClick() {
      this.timeModel = null //清空timePick
      this.time = nowTime
      this.getCounts(nowTime)
    },
    resizeChart() {
      this.chartInstance.resize()
    }
  },
  beforeDestroy() {
    // eslint-disable-next-line no-unused-expressions
    this.chartInstance && this.chartInstance.dispose()
  }
}
</script>
<style lang="scss" scoped>
.statisticTop {
  width: 100%;
  display: flex;
  margin: 20px;
  .btnClass {
    margin-left: 20px;
    .btn {
      margin-left: 10px;
    }
  }
}
.chart-main {
  width: 100%;
  height: 50vh;
}
</style>
